
import { withPixiApp, Container } from '@inlet/react-pixi'
import React from 'react'
import { connect } from 'react-redux'
import { projectLabelView as projectDuck } from 'ducks'
import PropTypes from 'prop-types'
import Constants from 'utils'
import { Point } from '../brushes'

const { normalPointsColor, sidePointsColor } = Constants

const paintPoint = (points, scale, move) => {
  return points.map((point, index) => {
    let iColor
    let oColor
    if (index === 0 || index === (points.size - 1)) {
      iColor = sidePointsColor.inner
      oColor = sidePointsColor.outer
    } else {
      iColor = normalPointsColor.inner
      oColor = normalPointsColor.outer
    }
    const moveHof = i => (x, y) => move(i, x, y)
    return (
      <Point
        key={index}
        point={point}
        scale={scale}
        move={moveHof(index)}
        innerColor={iColor}
        outerColor={oColor}
      />
    )
  })
}

const getEditPolygonPoint = (isEditHole, editHoleIndex, label, scale, move, moveHole) => {
  if (isEditHole) {
    const holes = label.interior
    if (editHoleIndex !== undefined && holes.length > editHoleIndex) {
      const points = holes[editHoleIndex]
      return paintPoint(points, scale, moveHole(editHoleIndex))
    }
  } else {
    const points = label.exterior
    return paintPoint(points, scale, move)
  }
}

const EditPolygonView = ({
  editHoleIndex,
  isEditHole,
  label,
  scale,
  move,
  moveHole,
}) => {
  return (
    <Container>
      {
        getEditPolygonPoint(isEditHole, editHoleIndex, label, scale, move, moveHole)
      }
    </Container>
  )
}

EditPolygonView.propTypes = {
  editHoleIndex: PropTypes.number,
  isEditHole: PropTypes.bool.isRequired,
  label: PropTypes.object.isRequired,
  scale: PropTypes.number.isRequired,
  move: PropTypes.func.isRequired,
  moveHole: PropTypes.func.isRequired,
}

EditPolygonView.defaultProps = {
  editHoleIndex: undefined,
}

const mapStateToProps = state => ({
  isEditHole: projectDuck.selectors.isEditPolygonHole(state),
  editHoleIndex: projectDuck.selectors.editHoleIndex(state),
})

const mapDispatchToProps = {
  move: projectDuck.creators.actionMovePoint,
  moveHole: projectDuck.creators.actionMoveHolePoint,
}

export default withPixiApp(connect(mapStateToProps, mapDispatchToProps)(EditPolygonView))
